package com.example.image.glide

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.LibraryGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

/**
 * 利用OkhttpClient来设置图片网络缓存
 */

@GlideModule
class OkHttpModule : LibraryGlideModule() {

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {

        var okhttpBuider = OkHttpClient.Builder()

        //获取外部存储目录
        var externalDirFile =Environment.getExternalStorageDirectory()
        if (externalDirFile.exists()){
            var cacheDir = "${externalDirFile.absolutePath}/cacheImage"
            var cacheFile =File(cacheDir)
            if(!cacheFile.exists()){
                cacheFile=File(cacheDir)
            }
            //设置缓存文件大小
            okhttpBuider.cache(Cache(cacheFile,250*1024*1024))

        }else{

            var appCacheDir = "${context.externalCacheDir?.absolutePath}/cacheImage"
            var cacheFile =File(appCacheDir)
            if(!cacheFile.exists()){
                cacheFile=File(appCacheDir)
            }
            //计算一下缓存大小
            var cacheSize =50*1024*1024L
            context.externalCacheDir?.totalSpace?.let {
                cacheSize=it/4L
            }
            okhttpBuider.cache(Cache(cacheFile,cacheSize))
        }

        //给Glide设置注册新的OkhttpClient
        registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(okhttpBuider.build()))
    }
}